import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from'@/components/Login/Login.vue'
/* 路由懒加载   npm install --save-dev @babel/plugin-syntax-dynamic-import*/
const Home = ()=>import( '@/components/Home/Home.vue')
const Welcome = ()=>import( '@/components/Welcome/Welcome.vue')
const Users = ()=>import( '@/components/User/Users.vue')
const Rights = ()=>import( '@/components/Power/Rights.vue')
const Roles = ()=>import( '@/components/Power/Roles.vue')
const CateGory = ()=>import( '@/components/Goods/CateGory.vue')
const Params = ()=>import( '@/components/Goods/Params.vue')
const GoodsList = ()=>import('@/components/Goods/List.vue')
const GoodsAdd = ()=>import('@/components/Goods/Add.vue')
const GoodsEdit = ()=>import('@/components/Goods/Edit.vue')
const Order = ()=>import('@/components/Order/Order.vue')
const Report = ()=>import('@/components/Report/Report.vue')

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: Login,
    meta:{
      title: '登录|雪碧后台管理'
    }
  },
  {
    path: '/home',
    name: 'home',
    component: Home,
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        component: Welcome,
        meta: {
          title: '欢迎光临'
        }
      },
      {
        path: '/users',
        component: Users
      },
      {
        path: '/rights',
        component: Rights
      },
      {
        path: '/roles',
        component: Roles
      },
      {
        path: '/categories',
        component: CateGory
      },
      {
        path: '/params',
        component: Params
      },
      {
        path: '/goods',
        component: GoodsList
      },
      {
        path: '/goods/add',
        component: GoodsAdd
      },
      {
        path: '/goods/edit',
        component: GoodsEdit
      },
      {
        path: '/orders',
        component: Order
      },{
        path: '/reports',
        component: Report
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  routes
})

/* 挂载全局前置守卫 */
/* to: Route: 即将要进入的目标 路由对象
from: Route: 当前导航正要离开的路由
next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
*/
const defaultTitle = '雪碧商城' //设置默认 title 头

router.beforeEach((to, from, next) => {
  // console.log(to, from);
  if (to.path === '/login') return next()
  // 获取token
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  // 否则放行

  /* 路由发生变化修改页面title */
   document.title = to.meta.title ? to.meta.title : defaultTitle
   next()
})

export default router
